var brandsChanged = false;
var productsChanged = false;


//get
function getCarProducts(){
	var vdata = $("#carPriceRequest").find("select").filter(":visible").serialize(); //serializeArray();
	console.log("vdata: " +  vdata);
	console.log("JSON.stringify(vdata): " +  JSON.stringify(vdata));
	
	/*
	var requestData = $("#carPriceRequest").serialize();
	console.log("requestData: " +  requestData);
	var requestValue = $("#carPriceRequest").val();
	console.log("requestValue: " +  requestValue);
	console.log("jsonDataE: " +  JSON.stringify($("#carPriceRequest")));
	var jsonData = JSON.stringify(requestData);
	console.log("jsonData: " +  jsonData);
	*/
	
	$.ajax({
		type: "get",
		data:  vdata, 
		url: "/products",
		dataType: "json",
		//contentType: "application/json",
		success: function(response){
			console.log("response: " +  response);
		},
		fail: function(error){
			console.log("error: " +  error);
		},
	});
}

function brandsUpdated(){
	brandsChanged = true;
}

//post
function updateSelectOptions(selectItem){
	console.log("selectItem.id: " + selectItem.id);
	//if selectItem ==  $("#products")
	if(selectItem.id =="products" && !brandsChanged){//if there is no brands chagne, no need to update the Product select options
		return;
	}
	if(selectItem.id =="displacements" && !productsChanged){//if there is no brands chagne, no need to update the Product select options
		return;
	}
	var url = "/" + selectItem.id;
	var vdata = $("#carPriceRequest").find("select").filter(":visible").serializeArray(); //serialize();
	console.log("vdata: " +  vdata);
	
	$.ajax({
		type: "post",
		data:  vdata, 
		url: url,
		dataType: "json",
		//contentType: "application/json",
		success: function(response){
			console.log("response: " +  response);
			//var responseData = JSON.stringify(response);
			$.each(response, function(index, option){
				console.log(option.id + "," + option.name);
				//selectItem.append($("<option></option>").prop("value", option.id).text(option.name));
				selectItem.add(new Option(option.name, option.id));
			});
		},
		error: function(error){
			console.log("error: " +  JSON.stringify(error));
			alert('Failure to connect the Server!');
		},
	});
	//refresh the flag
	if(selectItem.id =="products"){
		brandsChanged = false;
	}
	if(selectItem.id =="displacements"){
		productsChanged = false;
	}
}

function productsUpdated(){
	productsChanged = true;
}

